﻿using KPIS.GERP.Models.Class;
using KPIS.GERP.Models.ICM;
using System;
using System.Linq;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Data;
using KPIS.GERP.Models.SYS;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class BidController : Controller
    {
        public ActionResult Index(int PrId)
        {
            var service = new BidService.BidServiceClient();
            //var service2 = new PurchaseRequestService.PurchaseRequestServiceClient();
            //var RecordStatus = service2.Select(new PurchaseRequest { PrId = PrId }, null).FirstOrDefault().RecordStatus;
            var model = service.SelectBid(new Models.ICM.Bid { PrId = PrId, RecordStatus = "!D" }, null);

            //ViewBag.bEditable = RecordStatus == KPIS.GERP.Models.SYS.RecordStatus.WaitStatus || RecordStatus == KPIS.GERP.Models.SYS.RecordStatus.ReturnedStatus;

            return View(model);//new[] { "BidEmp", "BidJobSite", "ConfirmEmp", "CancelEmp" })
        }

        public ActionResult Details(int id, string layout = "Empty", bool nolayout = false, bool showApproveButton = false)
        {
            var service = new BidService.BidServiceClient();
            var model = service
                .SelectBid(new Models.ICM.Bid { BidId = id }, new[]
                {
                    "PurchaseRequest.Priority", 
                    "PurchaseRequest.DurationType", 
                    "PurchaseRequest.DurationCount", 
                    "PurchaseRequest.YearType", 
                    "PurchaseRequest.MasPurchaseType", 
                    "PurchaseRequest.MasPurchaseMethod", 
                    "BidEmp", 
                    "BidJobSite", 
                    "ConfirmEmp", 
                    "CancelEmp"
                })
                .FirstOrDefault(); 


            ViewBag.bEditable = model.RecordStatus == KPIS.GERP.Models.SYS.RecordStatus.WaitStatus || model.PurchaseRequest.RecordStatus == KPIS.GERP.Models.SYS.RecordStatus.ReturnedStatus;
            bool useNoLayout = nolayout || "Empty" == layout;
            ViewBag.Layout = Class.GimsUtilities.GetLayout(useNoLayout ? "Empty" : layout);
            ViewBag.NoLayout = useNoLayout;
            ViewBag.ShowApproveButton = showApproveButton;
            return View(model);
        }

        public ActionResult Create(int PrId, bool showApproveButton = false)
        {
            //var service = new BidService.BidServiceClient();
            //var modelMain = service.Select(new Models.ICM.Bid { PrId = PrId }, null).FirstOrDefault();
            var model = new Models.ICM.Bid();
            model.PrId = PrId;
            model.BidDate = DateTime.Today;
            model.ReceiveType = "F";
            model.ReceivePlace = "สถาบันรับรองคุณภาพสถานพยาบาล (องค์การมหาชน)";
            model.OfferPlace = "สถาบันรับรองคุณภาพสถานพยาบาล (องค์การมหาชน)";
            model.DisclosePlace = "สถาบันรับรองคุณภาพสถานพยาบาล (องค์การมหาชน)";
            ViewBag.showApproveButton = showApproveButton;

            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Create(Bid model, bool showApproveButton = false)
        {
            if (!model.OfferDateStart.HasValue) ModelState.AddModelError("OfferDateStart", "กรุณากำหนดวันที่ยื่นเอกสาร");
            if (!model.OfferDateEnd.HasValue) ModelState.AddModelError("OfferDateEnd", "กรุณากำหนดวันที่ยื่นเอกสาร");

            if (model.OfferDateStart.HasValue && model.OfferDateStart.Value.Year < 2500)
            {
                model.OfferDateStart = model.OfferDateStart.Value.AddYears(543);
            }

            if (model.OfferDateEnd.HasValue && model.OfferDateEnd.Value.Year < 2500)
            {
                model.OfferDateEnd = model.OfferDateEnd.Value.AddYears(543);
            }

            ViewBag.showApproveButton = showApproveButton;
            try
            {
                if (ModelState.IsValid)
                {
                    model.BidEmpId = Class.GimsMembership.CurrentEmpId;
                    var service = new BidService.BidServiceClient();
                    var id = service.InsertBid(model, Class.GimsMembership.CurrentEmpId );

                    return RedirectToAction("Details", new { Id = id, showApproveButton });
                }

                return View(model);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Empty", ex.Message);
                return View(model);
            }
        }

        public ActionResult Edit(int Id, bool showApproveButton = false)
        {
            var service = new BidService.BidServiceClient();
            var model = service.SelectBid(new Models.ICM.Bid { BidId = Id }, new[] { "BidEmp", "BidJobSite", "ConfirmEmp", "CancelEmp" }).FirstOrDefault();
            ViewBag.showApproveButton = showApproveButton;
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(int Id, Models.ICM.Bid model, bool showApproveButton = false)
        {
            ViewBag.showApproveButton = showApproveButton;
            try
            {
                if (ModelState.IsValid)
                {
                    model.BidEmpId = Class.GimsMembership.CurrentEmpId;
                    var service = new BidService.BidServiceClient();
                    service.UpdateBid(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { Id = model.BidId, showApproveButton });
                }

                return View(model);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Empty", ex.Message);
                return View(model);
            }
        }

        public ActionResult Delete(int id)
        {
            try
            {
                var service = new BidService.BidServiceClient();
                var PrId = service.SelectBid(new Models.ICM.Bid { BidId = id }, null).FirstOrDefault().PrId;
                service.DeleteBid(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Index", new { PrId = PrId });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAll(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new BidService.BidServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.DeleteBid(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("Empty", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");
                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Empty", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }

        public void Report(int BidId)
        {
            var service = new BidService.BidServiceClient();
            var model = service.SelectBid(new Models.ICM.Bid { BidId = BidId},null).FirstOrDefault();
            var model1 = service.ApproveName(BidId);

            Dictionary<string, string> fields = new Dictionary<string, string>();
            Dictionary<string, DataTable> Table = new Dictionary<string, DataTable>();
            MailMerge mailMerge = new MailMerge();

                fields.Add("BidName", model.Name);
                fields.Add("OfferDateStart", model.OfferDateStart != null ? model.OfferDateStart.Value.ToLongDateString() : "");
                fields.Add("OfferDateEnd", model.OfferDateEnd != null ? model.OfferDateEnd.Value.ToLongDateString() : "");
                fields.Add("OfferTimeStart", model.OfferDateTimeStart != null ? model.OfferDateTimeStart.Value.ToLongTimeString() : "");
                fields.Add("OfferTimeEnd", model.OfferDateTimeEnd != null ? model.OfferDateTimeEnd.Value.ToLongTimeString() : "");
                fields.Add("OfferPlace", model.OfferPlace);
                fields.Add("DiscloseDate", model.DiscloseDate != null ? model.DiscloseDate.Value.ToLongDateString() : "");
                fields.Add("DiscloseTime", model.DiscloseTime.ToString());
                fields.Add("ReceivePlace", model.ReceivePlace);
                fields.Add("ReceiveDateStart", model.ReceiveDateStart != null ? model.ReceiveDateStart.Value.ToLongDateString() : "");
                fields.Add("ReceiveDateEnd", model.ReceiveDateEnd != null ? model.ReceiveDateEnd.Value.ToLongDateString() : "");
                fields.Add("AnnounceDate", model.AnnounceDate != null ? model.AnnounceDate.Value.ToLongDateString() : "");
                fields.Add("ApproverName", model1[0]);
                fields.Add("ApproverPositionName", model1[1]);

                string strTemplatePath = Server.MapPath("~/Templates/ประกาศ.docx");
                string strSaveAsPath = Server.MapPath("~/Temp/");
                string strSaveAsFileName = string.Format("ประกาศ{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));

                if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, null, null))
                {
                    Response.Clear();
                    Response.ContentType = "text/plain";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + strSaveAsFileName);
                    Response.WriteFile(strSaveAsPath + strSaveAsFileName);
                    Response.Flush();
                    System.IO.File.Delete(strSaveAsPath + strSaveAsFileName);                    
                    Response.End();
                    //mailMerge.SaveFileToClient(strSaveAsPath, strSaveAsFileName, true);
                }
        }

        public void BidderReport(int id)
        {
            var service = new BidService.BidServiceClient();
            Dictionary<string, string> fields = new Dictionary<string, string>();
            Dictionary<string, DataTable> Table = new Dictionary<string, DataTable>();
            MailMerge mailMerge = new MailMerge();

            var models = service.SelectBidder(new Models.ICM.Bidder { BidId = id }, new[] { "Bid", "MasContact" }).ToList();

            if (models == null || models.Count == 0)
            {
                return;
            }
            var model = models.FirstOrDefault();
            string BidCount = models.Count().ToString();
            var selectApproved = service.ApproveName(id);

            string names = string.Empty;

            for (int i = 0; i < models.Count; i++)
            {
                var item = models[i];

                if (i == models.Count - 1)
                {
                    names += (i + 1).ToString() + ". " + models[i].MasContact.NameTh ;
                }
                else
                {
                    names += (i + 1).ToString() + ".  " + models[i].MasContact.NameTh + System.Environment.NewLine;
                }
            }

            fields.Add("BidName", model.Bid.Name == null ? "" : model.Bid.Name);
            fields.Add("ConfirmDate", model.Bid.ConfirmDate == null ? "" : model.Bid.ConfirmDate.Value.ToLongDateString());
            fields.Add("OfferDateStart", model.Bid.OfferDateStart == null ? "" : model.Bid.OfferDateStart.Value.ToLongDateString());
            fields.Add("OfferDateEnd", model.Bid.OfferDateEnd == null ? "" : model.Bid.OfferDateEnd.Value.ToLongDateString());
            fields.Add("OfferTimeStart", model.Bid.OfferTimeStart == null ? "" : model.Bid.OfferTimeStart.ToString());
            fields.Add("OfferTimeEnd", model.Bid.OfferTimeEnd == null ? "" : model.Bid.OfferTimeEnd.ToString());
            fields.Add("BidderCount", BidCount);
            fields.Add("RightBidderCount", BidCount);
            fields.Add("BidderNames", names);
            fields.Add("AnnounceDate", model.Bid.AnnounceDate == null ? "" : model.Bid.AnnounceDate.Value.ToLongDateString());
            fields.Add("ApproverName", selectApproved[0]);
            fields.Add("ApproverPositionName", selectApproved[1]);


            string strTemplatePath = Server.MapPath("~/Templates/ประกาศรายชื่อผู้ผ่านการคัดเลือก.docx");
            string strSaveAsPath = Server.MapPath("~/Temp/");
            string strSaveAsFileName = string.Format("ประกาศรายชื่อผู้ผ่านการคัดเลือก{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));


            if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, null))
            {
                Response.Clear();
                Response.ContentType = "text/plain";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + strSaveAsFileName);
                Response.WriteFile(strSaveAsPath + strSaveAsFileName);
                Response.Flush();
                System.IO.File.Delete(strSaveAsPath + strSaveAsFileName);
                Response.End();
                //mailMerge.SaveFileToClient(strSaveAsPath, strSaveAsFileName, true);
            }

        }

        public void PriceReport(int id)
        {
            var service = new BidService.BidServiceClient();
            Dictionary<string, string> fields = new Dictionary<string, string>();
            Dictionary<string, DataTable> Table = new Dictionary<string, DataTable>();
            MailMerge mailMerge = new MailMerge();

            var modelBidder = service.SelectBidder(new Models.ICM.Bidder { BidId = id }, new[] { "Bid", "MasContact" }).ToList();

            if (modelBidder != null)
            {
                var model = modelBidder.FirstOrDefault();
                var BidderWin = modelBidder.Where(x => x.WinnerStatus == "1").ToList();

                var nIndex = 1;
                string names = string.Empty;
                foreach (var m in BidderWin)
                {
                    var modelWin = service.SelectBidderQuotation(new Models.ICM.BidderQuotation { BidderId = m.BidderId, Selected = "1" }, new[] { "Bidder", "Bidder.Bid", "Bidder.MasContact" }).ToList();
                    if (modelWin != null)
                    {
                        for (int i = 0; i < modelWin.Count; i++)
                        {
                            var SelmodelWin = modelWin.FirstOrDefault();
                            decimal? price = modelWin.Sum(x => x.Price) == null ? 0 : modelWin.Sum(x => x.Price);
                            string name = (i + 1) + ". " + SelmodelWin.Bidder.MasContact.NameTh == null ? "" : SelmodelWin.Bidder.MasContact.NameTh;
                            names = names + (name + " เป็นเงิน " + price.ToString() + " บาท " + (nIndex < BidderWin.Count ? System.Environment.NewLine : "")) + "\t";
                            nIndex++;
                        }
                    }
                }

                fields.Add("BidName", model.Bid.Name == null ? "" : model.Bid.Name);
                fields.Add("BidCode", model.Bid.Code == null ? "" : model.Bid.Code);
                fields.Add("ConfirmDate", model.Bid.ConfirmDate == null ? "" : model.Bid.ConfirmDate.Value.ToLongDateString());
                fields.Add("BidderName", names);

                string strTemplatePath = Server.MapPath("~/Templates/ประกาศผลการสอบราคาฯ.docx");
                string strSaveAsPath = Server.MapPath("~/Temp/");
                string strSaveAsFileName = string.Format("ประกาศผลการสอบราคาฯ{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));


                if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, null))
                {
                    Response.Clear();
                    Response.ContentType = "text/plain";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + strSaveAsFileName);
                    Response.WriteFile(strSaveAsPath + strSaveAsFileName);
                    Response.Flush();
                    System.IO.File.Delete(strSaveAsPath + strSaveAsFileName);
                    Response.End();
                }
            }
        }

        public void OfferReport(int id, int PprId)
        {
            var service = new BidService.BidServiceClient();
            var serviceCommittee = new CommitteeService.CommitteeServiceClient();
            var servicePrePurchaseRequest = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
            Dictionary<string, string> fields = new Dictionary<string, string>();
            Dictionary<string, DataTable> Table = new Dictionary<string, DataTable>();
            MailMerge mailMerge = new MailMerge();
            var model = service.OfferReport(id);
            var modelPr = servicePrePurchaseRequest.Select(new PrePurchaseRequest{PprId = PprId}, null).FirstOrDefault();
            var model1 = serviceCommittee.Select(new Committee() { CommitteeGroupId = modelPr.CommitteeGroupId, RecordStatus = "!" + RecordStatus.DeletedStatus }
                , new[] { "CommitteePosition", "Employee.Position" }).OrderBy(m => m.ComPositionId).ToList();
            var modelAllBidder = service.SelectBidder(new Bidder() { BidId = id }, new[] { "MasContact" }).ToList();
            var modelOfferBidder = service.SelectBidder(new Bidder() { BidId = id, OfferStatus = "1" }, new[] { "MasContact" }).ToList();

            fields.Add("PrName", model[0]);
            fields.Add("AnnounceDate", model[3]);
            fields.Add("offerStartDate", model[1]);
            fields.Add("OfferEndDate", model[2]);
            fields.Add("CountContact", modelAllBidder.Count.ToString());
            fields.Add("CountOffer", modelOfferBidder.Count.ToString());

            string AllBidder = "";

            for (int i = 0; i < modelAllBidder.Count; i++)
            {
                var item = modelAllBidder[i];

                if (i == modelAllBidder.Count - 1)
                {
                    AllBidder += (i + 1).ToString() + ". " + modelAllBidder[i].MasContact.NameTh;
                }
                else
                {
                    AllBidder += (i + 1).ToString() + ". " + (modelAllBidder[i].MasContact.NameTh) + System.Environment.NewLine + "\t"; 
                }
            }

            string strOfferBidder= "";

            for (int i = 0; i < modelOfferBidder.Count; i++)
            {
                var item = modelOfferBidder[i];

                if (i == modelOfferBidder.Count - 1)
                {
                    strOfferBidder += (i + 1).ToString() + ". " + modelOfferBidder[i].MasContact.NameTh;
                }
                else
                {
                    strOfferBidder += (i + 1).ToString() + ". " + (modelOfferBidder[i].MasContact.NameTh) + System.Environment.NewLine + "\t";
                }
            }

            fields.Add("OfferBidder", strOfferBidder);
            fields.Add("AllBidder", AllBidder);

            for (int i = 0; i < model1.Count; i++)
            {
                string CommitteePosName =  model1[i].CommitteePosition.LookUpName;
                string CommitteeName = model1[i].Employee.FullName;
                string CommiteeEmpPosName = model1[i].Employee.Position.Name;

                fields.Add("CommittePosName" + (i + 1).ToString(), CommitteePosName);
                fields.Add("CommitteName" + (i + 1).ToString(), CommitteeName);
                fields.Add("EmpPositionName" + (i + 1).ToString(), CommiteeEmpPosName);
            }

            string strTemplatePath = Server.MapPath("~/Templates/รายงานผลการรับซอง.docx");
            string strSaveAsPath = Server.MapPath("~/Temp/");
            string strSaveAsFileName = string.Format("รายงานผลการรับซอง{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));

            if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, null))
            {
                Response.Clear();
                Response.ContentType = "text/plain";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + strSaveAsFileName);
                Response.WriteFile(strSaveAsPath + strSaveAsFileName);
                Response.Flush();
                System.IO.File.Delete(strSaveAsPath + strSaveAsFileName);
                Response.End();
            }
        }
    }
}
